var JavaScriptObfuscator = require('javascript-obfuscator');
var fs = require("fs");

var publishFolder = "../publish";
var indexFile = "../index.html";
var sourceFolders = ["css", "fonts", "icons", "images", "modules"];

var indexStr = fs.readFileSync(indexFile, "utf8");
var reg = /<script src="(.+?)><\/script>/g;
var scripts = indexStr.match(reg);
indexStr = indexStr.replace(reg, "");

var libJs = "";
var outputJs = "";

for(var i = 0; i < scripts.length; i++) {
    var s = scripts[i].match(/"(.+?)"/)[0];
    s = s.replace(/"/g, "");
    s = "." + s;
    console.log(s);
    //if(s.indexOf("lib/") > -1) {
    //    libJs += fs.readFileSync(s, "utf8");
    //} else {
        outputJs += fs.readFileSync(s, "utf8");
    //}
}

//outputJs = outputJs.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
//outputJs = outputJs.replace(/\s/g,"");//去掉回车换行

//清空创建发布文件夹
deleteFolderRecursive(publishFolder);
fs.mkdirSync(publishFolder);


indexStr = indexStr.replace('</head>',  '<script src="./main.min.js"></script></head>')
fs.writeFileSync(publishFolder + "/index.html", indexStr);

for(var i = 0; i < sourceFolders.length; i++) {
    copyDir("../" + sourceFolders[i], publishFolder + "/" + sourceFolders[i]);
}

var obfuscationResult = JavaScriptObfuscator.obfuscate(outputJs,
    {
        compact: true,
        controlFlowFlattening: false,
        deadCodeInjection: false,
        debugProtection: false,
        debugProtectionInterval: false,
        disableConsoleOutput: true,
        identifierNamesGenerator: 'hexadecimal', //hexadecimal or mangled
        log: false,
        renameGlobals: false,
        rotateStringArray: true,
        selfDefending: true,
        stringArray: true,
        stringArrayEncoding: false,
        stringArrayThreshold: 0.75,
        unicodeEscapeSequence: false
    }
);

//fs.writeFileSync(publishFolder + "/main.min.js", obfuscationResult.getObfuscatedCode());
fs.writeFileSync(publishFolder + "/main.min.js", outputJs);


//删除文件夹
function deleteFolderRecursive(path) {
    if( fs.existsSync(path) ) {
        fs.readdirSync(path).forEach(function(file) {
            var curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};

/*
 * 复制目录、子目录，及其中的文件
 * @param src {String} 要复制的目录
 * @param dist {String} 复制到目标目录
 */
function copyDir(src, dist, callback) {
    fs.access(dist, function(err){
        if(err){
            // 目录不存在时创建目录
            fs.mkdirSync(dist);
        }
        _copy(null, src, dist);
    });

    function _copy(err, src, dist) {
        if(err){
            callback(err);
        } else {
            fs.readdir(src, function(err, paths) {
                if(err){
                    callback(err)
                } else {
                    paths.forEach(function(path) {
                        var _src = src + '/' +path;
                        var _dist = dist + '/' +path;
                        fs.stat(_src, function(err, stat) {
                            if(err){
                                callback(err);
                            } else {
                                // 判断是文件还是目录
                                if(stat.isFile()) {
                                    fs.writeFileSync(_dist, fs.readFileSync(_src));
                                } else if(stat.isDirectory()) {
                                    // 当是目录是，递归复制
                                    copyDir(_src, _dist, callback)
                                }
                            }
                        })
                    })
                }
            })
        }
    }
}